/*
 * Copyright (c) 2018-2999 深圳市阿毛科技有限公司 All rights reserved.
 *
 * https://www.lamyz.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.lam.mall.api.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lam.common.base.domain.Result;
import com.lam.common.context.TokenUtils;
import com.lam.common.pay.config.DvyConfig;
import com.lam.common.utils.JsonUtil;
import com.lam.common.utils.StringUtils;
import com.lam.framework.operLog.annotation.Log;
import com.lam.mall.app.vo.DeliveryVo;
import com.lam.mall.entity.Delivery;
import com.lam.mall.entity.Order;
import com.lam.mall.service.DeliveryService;
import com.lam.mall.service.OrderService;

import cn.hutool.http.HttpUtil;

/**
 * @author lam
 */
@RestController
@RequestMapping("/${frontPath}/delivery")
@Log(title = "查看物流接口")
public class DeliveryApiController {

	@Autowired
	private DeliveryService deliveryService;
	@Autowired
	private OrderService orderService;

    /**
     * 查看物流接口
     * 根据订单号查看物流
     */
    @GetMapping("/check")
    @Log(oper = "查看物流")
    public Result checkDelivery(String orderNumber) {

    	Order order = orderService.selectSimpleByOrderNo(orderNumber);
    	if (order == null || !StringUtils.equals(TokenUtils.getLoginUserid(), order.getUserId())) {
    		return Result.fail("未查询到该订单物流！");
        }
    	Delivery delivery = deliveryService.selectById(order.getDvyId());
    	String dvyUrl = DvyConfig.getDvyUrl(order.getDvyFlowNo(), delivery.getCode());
    	String url = delivery.getQueryUrl().replace("{dvyFlowId}", order.getDvyFlowNo());
    	String deliveryJson = HttpUtil.get(url);
    	DeliveryVo deliveryVo = JsonUtil.toJavaObject(deliveryJson, DeliveryVo.class);
    	deliveryVo.setDvyFlowId(order.getDvyFlowNo());
    	deliveryVo.setCompanyHomeUrl(delivery.getCompanyHomeUrl());
    	deliveryVo.setCompanyName(delivery.getDvyName());
    	deliveryVo.setDvyUrl(dvyUrl);
        return Result.ok(deliveryVo);
    }
}
